package com.kx.smsplatform.controller;

import com.kx.smsplatform.service.InterfaceService;
import com.kx.smsplatform.util.R;
import com.kx.smsplatform.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author Sun
 * @Date 2021/6/30 17:49
 */
@RestController
public class InterfaceController {
    @Autowired
    private InterfaceService interfaceService;

    @RequestMapping("/smsInterface")
    public ResultVO smsInterface(@RequestBody Map map, HttpServletRequest request) {

        //1.获取客户端的真实ip
        String ip = getRealRemoteAddr(request);
        //2.将ip封装到map中
        map.put("ip", ip);
        //3.调用service层校验6个参数,校验出现异常直接抛出去
        interfaceService.checkParameterAndSendMessage2MQ(map);

        return R.OK(); //能走到这步说明数据都是正常的数据
    }

    /**
     * 通过Nginx反向代理后,通过Nginx拿到的去其实是Nginx的ip，所以需要通过请求头获取客户端的真实ip
     *
     * @param request
     * @return
     */
    private String getRealRemoteAddr(HttpServletRequest request) {
        //如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        //apache http做代理时一般会加上Proxy-Client-IP请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        //apache http做代理时，weblogic插件加上WL-Proxy-Client-IP。
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        //部分代理服务器加的请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        //分代理服务器加的请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        //nginx代理一般会加上此请求头
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        //当不使用代理获取的ip
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }
}
